package com.sz.virtualbank.common.exception;

import java.util.stream.Collectors;

import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import com.sz.virtualbank.common.result.CommonResponse;

import lombok.extern.slf4j.Slf4j;

/**
 * 全局异常处理器
 *
 * @author Claude
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理业务异常
     *
     * @param e 业务异常
     * @return 响应结果
     */
    @ExceptionHandler(BusinessException.class)
    public CommonResponse<?> handleBusinessException(BusinessException e) {
        log.error("业务异常：{}", e.getMessage(), e);
        return CommonResponse.buildFailure(e.getCode(), e.getMessage());
    }

    /**
     * 处理参数校验异常
     *
     * @param e 参数校验异常
     * @return 响应结果
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public CommonResponse<?> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        String message = e.getBindingResult().getAllErrors().stream()
                .map(ObjectError::getDefaultMessage)
                .collect(Collectors.joining("; "));
        log.error("参数校验异常：{}", message, e);
        return CommonResponse.buildFailure(4000, message);
    }

    /**
     * 处理参数绑定异常
     *
     * @param e 参数绑定异常
     * @return 响应结果
     */
    @ExceptionHandler(BindException.class)
    public CommonResponse<?> handleBindException(BindException e) {
        String message = e.getBindingResult().getAllErrors().stream()
                .map(ObjectError::getDefaultMessage)
                .collect(Collectors.joining("; "));
        log.error("参数绑定异常：{}", message, e);
        return CommonResponse.buildFailure(4000, message);
    }

    /**
     * 处理约束违反异常
     *
     * @param e 约束违反异常
     * @return 响应结果
     */
//    @ExceptionHandler(ConstraintViolationException.class)
//    public CommonResponse<?> handleConstraintViolationException(ConstraintViolationException e) {
//        String message = e.getConstraintViolations().stream()
//                .map(ConstraintViolation::getMessage)
//                .collect(Collectors.joining("; "));
//        log.error("约束违反异常：{}", message, e);
//        return CommonResponse.buildFailure(4000, message);
//    }
//

    /**
     * 处理未知异常
     *
     * @param e 未知异常
     * @return 响应结果
     */
    @ExceptionHandler(Exception.class)
    public CommonResponse<?> handleException(Exception e) {
        log.error("系统异常：{}", e.getMessage(), e);
        return CommonResponse.buildFailure(5000, "系统异常，请稍后再试");
    }
}
